package com.heima.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.mapper.WmUserMapper;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.service.WmUserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;


@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    /**
     * 登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(WmUserDto dto) {
        //1.参数校验
        if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.根据用户名查询用户信息，获取盐
        WmUser wmUser = getOne(Wrappers.<WmUser>lambdaQuery()
                        .eq(WmUser::getName,dto.getName())
//                .eq(AdUser::getStatus,AppHttpCodeEnum.ADCHANNEL_ADUSER_ISNOTEXIT_ERROR)
                        .eq(WmUser::getStatus, AdminConstants.ADUSER_NORMAL_STATUS)
        );
        //判断用户信息是否为空
        if (wmUser == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //获取数据库密码
        String pwd = wmUser.getPassword();
        //获取密码
        String password = dto.getPassword();
        //获取盐
        String salt = wmUser.getSalt();

        //3.加密并比对
        String hex = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if(!pwd.equals(hex)){
            CustException.cust(AppHttpCodeEnum.ADMIN_USER_NAMEORPWD_ERROR);
        }

        //4.更新登录时间
        wmUser.setCreatedTime(new Date());
        updateById(wmUser);

        //5生成token和用户信息返回给前端
        HashMap<String, Object> resultMap = new HashMap<>();
        String token = AppJwtUtil.getToken(wmUser.getId().longValue());
        resultMap.put("token",token);

        //用户信息
        //不能将密码和盐返回
        wmUser.setPassword(null);
        wmUser.setSalt(null);
        resultMap.put("user",wmUser);
        //返回结果
        return ResponseResult.okResult(resultMap);
    }

}
